/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
function searchReport()
{
    $("#reportsContainer").show("fast");
    $("#view_report_body").hide('fast');
    $('#buttons_container_list_add_report').hide('fast');
    $('#buttons_container_list').show("fast");
    var url = getBaseUrl()+'/index.php/reports/search';
    var reportname_email = $('#searchbox').val();
    var startDate = $('#startDate').val();
    var endDate = $('#endDate').val();
    var report_type_search = $('#report_type_search').val();
    var submitter_search = $('#submitter_search').val();
    var reportStatus = $('#reportStatus').val();
    var values = 'reportname_email='+reportname_email+'&startDate='+startDate+'&endDate='+endDate+'&report_type_search='+report_type_search+'&submitter_search='+submitter_search+'&reportStatus='+reportStatus;
    $("#report_search_spinner").show('fast');
    $.ajax({
        url: url,
        type: "POST",
        data: values,
        success: function(data){
    	    $('#reportsContainer').html(data);
    	    $("#report_search_spinner").hide('fast'); 
        }
    }); 
}
function updateCategoryTotal()
{
    var categoryArr = {};
	var defaultCurrency = $('#default_currency').val();
	var defaultExchangeRate = $('#default_exchange_rate').val();
    $('.totalcolumn').each(function(){
        var tr = $(this).parents('tr');
	    var category = tr.find('.categorycolumn').text();
	    var amount = tr.find('.totalcolumn').text();
       	if(typeof categoryArr[category]=='undefined')
      	{
       		 categoryArr[category] = parseFloat(amount);
      		 
      	}
      	else
      		categoryArr[category] += parseFloat(amount);
    });
    
	var htmlString='<h2>Total by category:</h2><ol>';
	var defaultCurrency = $('#default_currency').val();
	for (var name in categoryArr) {
		htmlString +='<li><label><strong>&nbsp;&nbsp;Total by '+name+' '+':</strong></label><span> <strong>' +parseFloat(categoryArr[name]).toFixed(2)+' '+defaultCurrency+'</strong></span></li>';
	}
	
	htmlString+='<ol>';
	
	return htmlString;
}
function getBaseUrl()
{
	var l = window.location;
	var base_url = l.protocol + "//" + l.host + "/" + l.pathname.split('/')[1];
	return base_url;
}
function addCommas(str) {
    var amount = new String(str);
    amount = amount.split("").reverse();

    var output = "";
    for ( var i = 0; i <= amount.length-1; i++ ){
        output = amount[i] + output;
        if ((i+1) % 3 == 0 && (amount.length-1) !== i)output = ',' + output;
    }
    return output;
}
$(document).ready(function() {
    $('#expense_tab').click(function(e) {
    	$('#newExpenseCurrentTab').val('expense_tab');
        $('#smallTabs_content_left').show('fast');
        $('#receiptSide').show('fast');
        $('#open_dialog_receipts3_panel').show('fast');
        $('#open_dialog_map_panel').hide('fast');
        $('#newExpense3_expenseForm').show('fast');
        $('#newExpense3_mileageForm').hide('fast');
        $('#newExpense3_timeForm').hide('fast');
        $('#newExpense3_multipleForm').hide('fast');
        $('#expense_tab').removeClass();
        $('#expense_tab').addClass('first current');
        $('#mileage_tab').removeClass();
        $('#time_tab').removeClass();
        $('#multiple_tab').removeClass();
        //$('#time_tab').addClass('hidden last');
    });
    $('#mileage_tab').click(function(e) {
    	$('#newExpenseCurrentTab').val('mileage_tab');
        $('#smallTabs_content_left').show('fast');
        $('#receiptSide').show('fast');
        $('#newExpense3_expenseForm').hide('fast');
        $('#open_dialog_receipts3_panel').hide('fast');
        $('#open_dialog_map_panel').show('fast');
        $('#newExpense3_mileageForm').show('fast');
        $('#newExpense3_timeForm').hide('fast');
        $('#newExpense3_multipleForm').hide('fast');
        $('#mileage_tab').removeClass();
        $('#mileage_tab').addClass('first current');
        $('#time_tab').removeClass();
        $('#expense_tab').removeClass();
        $('#multiple_tab').removeClass();
        //$('#expense_tab').addClass('hidden last');
    });
    $('#time_tab').click(function(e) {
    	$('#newExpenseCurrentTab').val('time_tab');
        $('#smallTabs_content_left').show('fast');
        $('#receiptSide').show('fast');
        $('#open_dialog_receipts3_panel').show('fast');
        $('#open_dialog_map_panel').hide('fast');
        $('#newExpense3_expenseForm').hide('fast');
        $('#newExpense3_mileageForm').hide('fast');
        $('#newExpense3_timeForm').show('fast');
        $('#newExpense3_multipleForm').hide('fast');
        $('#time_tab').removeClass();
        $('#time_tab').addClass('first current');
        $('#mileage_tab').removeClass();
        //$('#mileage_tab').addClass('hidden last');
        $('#expense_tab').removeClass();
        $('#multiple_tab').removeClass();
    });
    $('#multiple_tab').click(function(e) {
    	$('#newExpenseCurrentTab').val('multiple_tab');
        $('#newExpense3_expenseForm').hide('fast');
        $('#newExpense3_mileageForm').hide('fast');
        $('#newExpense3_multipleForm').show('fast');
        $('#newExpense3_timeForm').hide('fast');
        $('#smallTabs_content_left').hide('fast');
        $('#receiptSide').hide('fast');

        $('#multiple_tab').removeClass();
        $('#multiple_tab').addClass('first current');
        $('#mileage_tab').removeClass();
        $('#time_tab').removeClass();
        $('#expense_tab').removeClass();

    });
    
    $('#createexpense_button').click(function() {
                    $('#dialog_newExpense3').fadeIn(300);
                    $('body').append('<div id="mask"></div>');
                    $('#mask').fadeIn(300);
                    return false;
                });

                $(document).on('click', 'a.dialog_x, #mask', function() {
                    $('#mask, div#dialog_newExpense3').fadeOut(300, function() {
                        $('#mask').remove();
                    });
                    return false;
                });
                $(document).on('click', '.megaEdit', function() {
				        $('#dialog_megaEdit').fadeIn(300);
                        $('body').append('<div id="mask"></div>');
                        $('#mask').fadeIn(300);
                        return false;
				});
                $('#editMultiple_button').click(function() {
				    
                    if ($('.expensetable_checkbox:checked').length > 0)
                    {
					    $('#dialog_editMultiple').fadeIn(300);
               
                        $('body').append('<div id="mask"></div>');
                        $('#mask').fadeIn(300);
						
                        return false;
                    }
                });

                $(document).on('click', 'a.dialog_x, #mask', function() {
                    $('#mask, div#dialog_editMultiple, div#dialog_megaEdit').fadeOut(300, function() {
                        $('#mask').remove();
                    });
                    return false;
                });


                $('.qtip').click(function(e, ui) {
                    $(this).siblings().removeClass('current');
                    $(this).addClass('current');

                    if (($(e.target).parent().attr('data-tab')) == 'one')
                    {
                        $('.newExpense3_one').show('fast');
                        $('.newExpense3_few').hide('fast');
                        $('.newExpense3_lot').hide('fast');
                    }
                    else if (($(e.target).parent().attr('data-tab')) == 'few')
                    {
                        $('.newExpense3_one').hide('fast');
                        $('.newExpense3_few').show('fast');
                        $('.newExpense3_lot').hide('fast');
                    }
                    else if (($(e.target).parent().attr('data-tab')) == 'lot')
                    {
                        $('.newExpense3_one').hide('fast');
                        $('.newExpense3_few').hide('fast');
                        $('.newExpense3_lot').show('fast');
                    }
                });
				
				
                $('#mergeExpense_button').click(function() {
                    if ($('.expensetable_checkbox:checked').length == 2)
                    {
                        $('#dialog_mergeExpense').fadeIn(300);
                        $('body').append('<div id="mask"></div>');
                        $('#mask').fadeIn(300);
                        return false;
                    }
                    else if ($('.expensetable_checkbox:checked').length == 0)
                    {
                    }
                    else
                    {
                        $('#dialog_1').fadeIn(300);
                        $('body').append('<div id="mask"></div>');
                        $('#mask').fadeIn(300);
                        return false;
                    }
                });

                $(document).on('click', 'a.dialog_x, #mask', function() {
                    $('#mask, div#dialog_mergeExpense').fadeOut(300, function() {
                        $('#mask').remove();
                    });
                    return false;
                });

                $(document).on('click', 'a.dialog_x, #mask', function() {
                    $('#mask, div#dialog_1').fadeOut(300, function() {
                        $('#mask').remove();
                    });
                    return false;
                });
                

                $('#open_dialog_receipts3, .addReceiptIcon').click(function() {
                	var currentTab = $('#newExpenseCurrentTab').val();
                	if(currentTab == 'multiple_tab')
                		$('#mutilReceiptIdCurrent').val($(this).attr('id'));
                	var url = getBaseUrl()+'/index.php/expenses/loadreceipt';
                    //$('#spinter-delete').show();
                    var values = '';
                    $.ajax({
                        url: url,
                        type: "POST",
                        data: values,
                        success: function(data){
                    	    $('#receiptsD_allReceiptsContainer').html(data);
                        }
                    });
                     $('body').append('<div id="mask2"></div>');
					 $('#mask2').fadeIn(300);
					 $('#dialog_newExpense3').fadeOut(300);
                    $('#dialog_receipts3').fadeIn(300);

                   
                    return false;
                });
		    $('#open_dialog_map3').click(function() {
                      $('#dialog_map3').fadeIn(300);
                     $('body').append('<div id="mask2"></div>');
					$('#mask2').fadeIn(300);
					 $('#dialog_newExpense3').fadeOut(300);
                   
			
                   
                    return false;
                });

                $(document).on('click', 'a#receipt_close', function() {
                    $('#mask2, div#dialog_receipts3, div#dialog_map3').fadeOut(300, function() {
                        $('#mask2').remove();
                        $('#dialog_newExpense3').fadeIn(300);
                        $('body').append('<div id="mask"></div>');
                        $('#mask').fadeIn(300);
                    });
                    return false;
                });

//                $('#open_dialog_creditcard').click(function() {
//                    $('#dialog_creditcard').fadeIn(300);
//                    $('body').append('<div id="mask2"></div>');
//                    $('#mask2').fadeIn(300);
//                    return false;
//                });
				
                $(document).on('click', 'a#creditcard_close', function() {
                    $('#mask2, div#dialog_creditcard').fadeOut(300, function() {
                        $('#mask2').remove();
                        $('#dialog_newExpense3').fadeIn(300);
                        $('body').append('<div id="mask"></div>');
                        $('#mask').fadeIn(300);
                    });
                    return false;
                });

                $('#expenses_export_button').click(function() {
                    if ($('#expenses_export_button').attr('class') == 'button qtip current semwal_open')
                    {
                        $('#expenses_export_button').removeClass('semwal_open');
                        $('#reports_popup_export').fadeOut(300);
                    }
                    else
                    {
                        $('#reports_popup_export').fadeIn(300);
                        $('#expenses_export_button').addClass('semwal_open');
                    }
                    return false;
                });

                $(document).click(function() {
                    $('#reports_popup_export').fadeOut(300);
                });

              
});

function handleFileUpload(files)
{
   for (var i = 0; i < files.length; i++)
   {
        var fd = new FormData();
        fd.append('file', files[i]);
        sendFileToServer(fd);
 
   }
}
function sendFileToServer(formData)
{
    var uploadURL = getBaseUrl()+'/index.php/receipts/recieptupload'; //Upload URL
    $('#spinter-uploading').show();
    $.ajax({
        url: uploadURL,
        type: "POST",
        contentType:false,
        processData: false,
        cache: false,
        data: formData,
        success: function(data){
        $('#receiptsD_allReceiptsContainer').prepend(data);    
    	$('#spinter-uploading').hide();
        }
    });
 
}
function search()
{
	 var uploadURL = getBaseUrl()+'/index.php/expenses/search'; //Upload URL
	    $('#search_spinner').show();
	    var startDate = $('#startDate').val();
	    var endDate = $('#endDate').val();
	    var expense_status = $('#expense_status').val();
	    var expense_filter_categories = $('#expense_filter_categories').val();
	    var expense_filter_type = $('#expense_filter_type').val();
	    var expense_page = $('#expense_page').val();
	    var values = 'startDate='+startDate+'&endDate='+endDate+'&expense_status='+expense_status+'&expense_filter_categories='+expense_filter_categories+'&expense_filter_type='+expense_filter_type+'&expense_page='+expense_page;
	    $.ajax({
	        url: uploadURL,
	        type: "POST",
	        data: values,
	        success: function(data){
	    	    $('#tablecontainer').html(data);
	    	    $('#search_spinner').hide();
	        }
	    });
}
$(document).ready(function(){
	var obj = $("#qq-upload-drop-area");
	
	obj.on('dragenter', function (e)
	{
	    e.stopPropagation();
	    e.preventDefault();
	    $(this).css('border', '2px solid #0B85A1');
	});
	obj.on('dragover', function (e)
	{
	     e.stopPropagation();
	     e.preventDefault();
	});
	obj.on('drop', function (e)
	{
	     $(this).css('border', '2px dotted #0B85A1');
	     e.preventDefault();
	     var files = e.originalEvent.dataTransfer.files;
	 
	     //We need to send dropped files to Server
	     handleFileUpload(files);
	    
	});
	
	$(document).on('dragenter', function (e)
	{
	    e.stopPropagation();
	    e.preventDefault();
	});
	$(document).on('dragover', function (e)
	{
	  e.stopPropagation();
	  e.preventDefault();
	  obj.css('border', '2px dotted #0B85A1');
	});
	$(document).on('drop', function (e)
	{
	    e.stopPropagation();
	    e.preventDefault();
	});
	$('#file').change(function(){
		 var filedata = document.getElementById("file");
		 handleFileUpload(filedata.files);
	});
	$('#btnNewExpenseSave').click(function(){
		$('#sipnner_newexpense').show();
		
		var currentTab = $('#newExpenseCurrentTab').val();
		var values = '';
		var receiptId = $('#newExpenseReceiptId').val();
		switch(currentTab)
		{
			case 'expense_tab':
				var values = $('#expenseNewExpense').serialize()+'&'+$('#topMenuForm').serialize();
				values+='&tab=expense_tab&receiptId='+receiptId;
				break;
			case 'mileage_tab':
				var values = $('#newExpenseMileageForm').serialize()+'&'+$('#topMenuForm').serialize();
				values+='&tab=mileage_tab&receiptId='+receiptId;
				break;
			case 'time_tab':
				var values = $('#newExpenseTimeForm').serialize()+'&'+$('#topMenuForm').serialize();
				values+='&tab=time_tab&receiptId='+receiptId;
				break;
			case 'multiple_tab':
				var values = $('#newExpenseMultipleForm').serialize()+'&'+$('#topMenuForm').serialize();
				values+='&tab=multiple_tab';
				break;
		}
		var url = getBaseUrl()+'/index.php/expenses/addnewexpense';
	    $.ajax({
	        url: url,
	        type: "POST",
	        data: values,
	        success: function(data){
	    	
	        }
	    });
	    $('#expense_page').val('1');
	    search();
	    $('#sipnner_newexpense').hide();
	    $('#mask, div#dialog_newExpense3').fadeOut(300, function() {
            $('#mask').remove();
        });
	    $("#expenseNewExpense")[0].reset();
	    $("#newExpenseMileageForm")[0].reset();
	    $("#newExpenseTimeForm")[0].reset();	  
	    $("#newExpenseMultipleForm")[0].reset();	    
        return false;
	    
		
	});
	
	$(document).on('click','.attach_receipt_button' ,function (e){
		var idString = $(this).attr('id');
		var idArr = idString.split('_');
		var currentTab = $('#newExpenseCurrentTab').val();
		if(currentTab == 'multiple_tab')
		{
			var rowId = $('#mutilReceiptIdCurrent').val();
			var rowIdArr = rowId.split('_');
			$('#mutilReceiptId_'+rowIdArr[1]).val(idArr[3]);
			$('#'+rowId).attr('class','receiptIcon');
		}
		else{
			$('#newExpenseReceiptId').val(idArr[3]);
			$('#newExpenseReceiptImgId').attr('src',$('#img_receipt_'+idArr[3]).attr('src'));
		}
		 $('#mask2, div#dialog_receipts3, div#dialog_map3').fadeOut(300, function() {
             $('#mask2').remove();
             $('#dialog_newExpense3').fadeIn(300);
             $('body').append('<div id="mask"></div>');
             $('#mask').fadeIn(300);
         });
		 $('#open_dialog_receipts3_panel').hide();
		 $('#detach').show();
         return false;
	});
	$(document).on('click','#detach' ,function (e){
		$('#newExpenseReceiptImgId').attr('src', getBaseUrl()+'/images/icon-receipt_150_new.png');
		$('#open_dialog_receipts3_panel').show();
		$(this).hide()
	});
	$('#expense_filter_billable_claimCustomer_All').click(function(){
		$(this).attr('class','actived');
		$('#expense_filter_billable_claimCustomer_Billable').attr('class','');
		$('#expense_filter_billable_claimCustomer_ClaimCustomer').attr('class','');
		$('#expense_status').val('All');
		
	});
	$('#expense_filter_billable_claimCustomer_Billable').click(function(){
		$(this).attr('class','actived');
		$('#expense_filter_billable_claimCustomer_All').attr('class','');
		$('#expense_filter_billable_claimCustomer_ClaimCustomer').attr('class','');
		$('#expense_status').val('Billable');
	});
	$('#expense_filter_billable_claimCustomer_ClaimCustomer').click(function(){
		$(this).attr('class','actived');
		$('#expense_filter_billable_claimCustomer_All').attr('class','');
		$('#expense_filter_billable_claimCustomer_Billable').attr('class','');
		$('#expense_status').val('ClaimCustomer');
	});
	$(document).on('click','.pagingink' ,function (e){
		e.preventDefault();
		var hrefString = $(this).attr('href');
		var pageArray = hrefString.split('/');
		$('#expense_page').val(pageArray[pageArray.length-1]);
		search();
		
	});
	$(document).on('click','#btn_search' ,function (e){
		$('#filer_check_message').hide();
		if($('#startDate').val() > $('#endDate').val())
			{
			  $('#filer_check_message').show();
			  return false;
			}
		$('#expense_page').val('1');
		var filterType = $('#expense_filter_type').val();
		if(filterType == 'deleted')
		{
		   $('#expenses_deletebutton1').hide();
		   $('#undelete_buttons').show();
		}
		search();
	});
	$('#btn_reset').click(function(){
		$("#filter")[0].reset();
	});
	$(document).on('click','#expenses_selectall_checkbox' ,function (e){
		$('.expensetable_checkbox:input:checkbox').not(this).prop('checked', this.checked);
	});
	$(document).on('click','#delete_expense' ,function (e){
	    var deleteURL = getBaseUrl()+'/index.php/expenses/delete'; //Upload URL
	    //$('#spinter-delete').show();
	    var deleteString = '';
	    $('input:checkbox.expensetable_checkbox').each(function () {
	        var sThisVal = (this.checked ? $(this).val() : "");
	        deleteString+=sThisVal+'|';
	   });
	    $.ajax({
	        url: deleteURL,
	        type: "POST",
	        data: 'deleteString='+deleteString,
	        success: function(data){
	        }
	    });
	   search();
	});
	$(document).on('click','#undelete_buttons' ,function (e){
	    var deleteURL = getBaseUrl()+'/index.php/expenses/undelete'; //undelete url
	    //$('#spinter-delete').show();
	    var deleteString = '';
	    $('input:checkbox.expensetable_checkbox').each(function () {
	        var sThisVal = (this.checked ? $(this).val() : "");
	        deleteString+=sThisVal+'|';
	   });
	    $.ajax({
	        url: deleteURL,
	        type: "POST",
	        data: 'deleteString='+deleteString,
	        success: function(data){
	        }
	    });
	   search();
	});	
	$(document).on('click','#editMultiple_save' ,function (e){
	    var deleteURL = getBaseUrl()+'/index.php/expenses/editmultipleexpense'; 
	    //$('#spinter-delete').show();
	    var multipleString  = '';
	    $('input:checkbox.expensetable_checkbox').each(function () {
	        var sThisVal = (this.checked ? $(this).val() : "");
	        multipleString +=sThisVal+'|';
	   });
	    $.ajax({
	        url: deleteURL,
	        type: "POST",
	        data: $('#editMultiple_form').serialize()+'&multipleString='+multipleString,
	        success: function(data){
	        }
	    });
	   search();
	   $('#mask, div#dialog_editMultiple, div#dialog_megaEdit').fadeOut(300, function() {
           $('#mask').remove();
       });
       return false;
	});
	$('#addreport_button').click(function(){
		
		 var reportId = $('#report_selector').val();
		 if(reportId == 0)
			 return false;
		$('#addreport_spinner').show();
	    var uploadURL = getBaseUrl()+'/index.php/expenses/addexpensestoreport'; //Upload URL
	    //$('#spinter-delete').show();
	    var expenseString = '';
	    $('input:checkbox.expensetable_checkbox').each(function () {
	        var sThisVal = (this.checked ? $(this).val() : "");
	        expenseString +=sThisVal+'|';
	   });
	   
	    $.ajax({
	        url: uploadURL,
	        type: "POST",
	        data: 'expenseString='+expenseString+'&reportId='+reportId,
	        success: function(data){
	    		$('#addreport_spinner').hide();
	        }
	    });
	    search();
	});
});

$(function() {
	$( ".semwal_dtpicker" ).datepicker({ dateFormat: 'yy-mm-dd' });
	});
$(document).ready(function(){

    $(document).on('click', '#report_add_expense', function() {
    	var url = getBaseUrl()+'/index.php/reports/loadexpenseform';
        //$('#spinter-delete').show();
        var values = '';
        $.ajax({
            url: url,
            type: "POST",
            data: values,
            success: function(data){
        	    $('#dialog_expenses').html(data);
            }
        });
        $('#dialog_expenses').fadeIn(300);
        $('body').append('<div id="mask"></div>');
        $('#mask').fadeIn(300);
        return false;
    });
    $(document).on('click', 'a.dialog_x, #mask', function() {
        $('#mask, div#dialog_expenses').fadeOut(300, function() {
            $('#mask').remove();
        });
        return false;
    });
    $(document).on('click', '#addreport_button', function() {
    	var url = getBaseUrl()+'/index.php/reports/addexpensetoreport';
    	var htmlString = '';
    	var defaultCurrency = $('#default_currency').val();
    	var defaultExchangeRate = $('#default_exchange_rate').val();
    	
 	    $('input:checkbox.expensetable_checkbox').each(function () {
 	        //var sThisVal = (this.checked ? $(this).val() : "");
 	        if(this.checked)
        	{
 	        	var id = $(this).val();
 	        	var tr = $(this).parents('tr');
 	        	var date = tr.find('.datecolumn').text();
 	        	var receipt = tr.find('.receiptcolumn');
 	        	var receiptIcon = receipt.html();
 	        	var receiptId = receipt.attr('id');
 	        	var category = tr.find('.categorycolumn').text().trim();
 	        	var total = tr.find('.amountcolumn').text();
 	        	var currency = tr.find('.currencycolumn').text();
 	        	var exchangeRate = tr.find('.exchangeratecolumn').text();
 	        	var rate = parseFloat(defaultExchangeRate)/parseFloat(exchangeRate);
 	        	htmlString+='<tr class="hoverable odd last expense_item_tr" id="reportRow_'+id+'"><td class="delete-cell remove"></td><td class="editTransaction datecolumn lefttd">'+date+'</td><td width="10" class="receiptcolumn">'+receiptIcon+'</td><td class="editTransaction categorycolumn">'+category+'</td><td class="editTransaction currencycolumn righttd">'+total+' ('+currency+')'+'</td><td class="editTransaction currencycolumn righttd">'+'1 '+currency+' = '+parseFloat(rate).toFixed(2)+' '+defaultCurrency+'</td><td class="editTransaction totalcolumn righttd cash">'+(total*rate).toFixed(2)+'</td></tr>';
 	        	var receiptUrl = getBaseUrl()+'/index.php/reports/getreceiptbyexpenseid';
 	            var values = 'receiptId='+receiptId+'&date='+date+'&category='+category+'&total='+total+'&currency='+currency;
 	            $.ajax({
 	              url: receiptUrl,
 	              type: "POST",
 	              data: values,
 	              success: function(data){
 	          	    $('#attachedReceiptContainer').prepend(data);
 	              }
 	          });
        	}
 	   });
 	   $('#reporttable > tbody:last').before(htmlString);
 	    var categoryArr = {};
 	    var total = 0;
 	    $('.totalcolumn').each(function(){
 	        total += parseFloat(this.innerHTML);
 	    });
 	    $('#totals').text(total.toFixed(2)+' '+defaultCurrency);
 	    $('#total_value').val(total.toFixed(2));
 	  

 	   
 	    $('#total_by_category').html(updateCategoryTotal());
       $('.noitem').hide();
       $('#mask, div#dialog_expenses').fadeOut(300, function() {
           $('#mask').remove();
       });
       return false;
  
   });
    $(document).on('click', '#save_report,#submit', function() {
    	 var reportIdHidden = $('#reportIdHidden').val();
    	 var url ='';
    	 if(reportIdHidden == -1)
    	    url = getBaseUrl()+'/index.php/reports/insertnewreport';
    	 else
    		 url = getBaseUrl()+'/index.php/reports/updatereport';
    	 var expenseString = '';
    	 $('.expense_item_tr').each(function(){
    		 var trId = $(this).attr('id');
    		 var trIdSplit = trId.split('_');
    		 expenseString += trIdSplit[1]+'|';
  	    });
    	 var receiptString = '';
    	 $('.receiptimage').each(function(){
    		 var receiptId = $(this).attr('id');
    		 var receiptSplit = receiptId.split('_');
    		 receiptString += receiptSplit[1]+'|';
  	    });
    	 
    	 var values = $('#new_report_form').serialize()+'&expenseString='+expenseString+'&receiptString='+receiptString;
    	 var reportName = $('#text_title').text();
    	 var buttonThisId = $(this).attr('id');
    	 var status = '';
    	 if(submit = 'submit')
    		 status = 'Processing';
    	 else if(submit = 'save_report')
    		 status = 'Open';
    	 values+='&reportName='+reportName+'&status='+status;
    	
         $.ajax({
              url: url,
              type: "POST",
              data: values,
              success: function(data){
          	    $('#reportId').text(data);
          	    $('#reportIdHidden').val(data);
              }
          });    	
    });
    
    $(document).on('click', '.js_goToReport', function() {
    	var reportIdStr = $(this).parent('tr').attr('id');
    	var reportIdSplit = reportIdStr.split('_');
    	var url = getBaseUrl()+'/index.php/reports/openreport';
    	var values = 'reportId='+reportIdSplit[1];
        $("#reportsContainer").hide("fast");
        $("#view_report_body").show('fast');
        $('#buttons_container_list_add_report').show('fast');
        $('#buttons_container_list').hide("fast");
        $.ajax({
            url: url,
            type: "POST",
            data: values,
            success: function(data){
        	    $('#reportpreview').html(data);
            }
        }); 
    });
	$(document).on('click', '#new_report', function() {
        $("#reportsContainer").hide("fast");
        $("#view_report_body").show('fast');
        $('#buttons_container_list_add_report').show('fast');
        $('#buttons_container_list').hide("fast");
        var url = getBaseUrl()+'/index.php/reports/newreport';
        $.ajax({
            url: url,
            type: "POST",
            success: function(data){
        	    $('#reportpreview').html(data);
            }
        }); 
   }); 
	$(document).on('click', '#btn_report_search', function() {
		searchReport();
   });
	$(document).on('click', '#close', function() {
        $("#reportsContainer").show("fast");
        $("#view_report_body").hide('fast');
        $('#buttons_container_list_add_report').hide('fast');
        $('#buttons_container_list').show("fast");
	});
	$(document).on('click', '.remove', function() {
		var tr = $(this).closest('tr');
		 tr.fadeOut(300, function(){
	            tr.remove();
	 		   var defaultCurrency = $('#default_currency').val();
			    var total = 0;
		 	    $('.totalcolumn').each(function(){
		 	        total += parseFloat(this.innerHTML)
		 	    });
		 	   
		 	    $('#totals').text(parseFloat(total).toFixed(2)+' '+defaultCurrency);
		 	    $('#total_value').val(total);
		 	   $('#total_by_category').html(updateCategoryTotal());
	        });

	        return false;
	});	
	$(document).on('click','.selectall_checkbox' ,function (e){
		$('.reportstable_checkbox:input:checkbox').not(this).prop('checked', this.checked);
	});
	$(document).on('click','#button_deleteReports' ,function (e){
		var result = confirm("Are you sure to delete?");
		if (result==false) {
		    return false;
		}
	    var deleteURL = getBaseUrl()+'/index.php/reports/deletereport'; //Upload URL
	    //$('#spinter-delete').show();
	    var deleteString = '';
	    $('input:checkbox.reportstable_checkbox').each(function () {
	        var sThisVal = (this.checked ? $(this).val() : "");
	        deleteString+=sThisVal+'|';
	   });
	    $.ajax({
	        url: deleteURL,
	        type: "POST",
	        data: 'deleteString='+deleteString,
	        success: function(data){
	    	searchReport();
	        }
	    });
	  
	});
});
$(function() {
	$( ".semwal_dtpicker" ).datepicker({ dateFormat: 'yy-mm-dd' });
	});